
#include "MainJob.h"

Hook *g_hook = nullptr;
ZhTranslator *g_zhTranslator = nullptr;

QString traditionalToSimplified(const QString &traditionalText) {
    QString simplifiedText;
    for(const QChar &t : traditionalText) {
        const QChar &s = g_zhTranslator->Traditional2Simplified(t);
        simplifiedText.append(s);
    }
    return simplifiedText;
}

HFONT WINAPI FixedCreateFontW(int cHeight, int cWidth, int cEscapement, int cOrientation,
                              int cWeight, DWORD bItalic, DWORD bUnderline, DWORD bStrikeOut,
                              DWORD iCharSet, DWORD iOutPrecision, DWORD iClipPrecision,
                              DWORD iQuality, DWORD iPitchAndFamily, LPCWSTR pszFaceName)
{
    if (cHeight == 22 || cHeight == 26) {
        cHeight = 16;
        cWidth = 8;
        cWeight = 400;
    }

    // unhook
    g_hook->CloseLibFuncHookJmp("gdi32.dll", "CreateFontW");
    HFONT ret = CreateFontW(cHeight, cWidth, cEscapement, cOrientation,
                            cWeight, bItalic, bUnderline, bStrikeOut,
                            GB2312_CHARSET, iOutPrecision, iClipPrecision,
                            iQuality, iPitchAndFamily, L"SimSun");
    // hook
    g_hook->LibFuncHookJmp("gdi32.dll", "CreateFontW", (void *)FixedCreateFontW);

    return ret;
}

WINBOOL WINAPI FixedTextOutW(HDC hdc, int x, int y, LPCWSTR lpString, int c)
{
    std::wstring wstr(lpString);
    QString traditionalText = QString::fromStdWString(wstr);
    QString simplifiedText = traditionalToSimplified(traditionalText);
    LPCWSTR outLpString = simplifiedText.toStdWString().c_str();

    // unhook
    g_hook->CloseLibFuncHookJmp("gdi32.dll", "TextOutW");
    WINBOOL ret = TextOutW(hdc, x, y, outLpString, c);
    // hook
    g_hook->LibFuncHookJmp("gdi32.dll", "TextOutW", (void *)FixedTextOutW);

    return ret;
}

MainJob::MainJob(QObject *parent)
    : QObject(parent)
{

}

MainJob::~MainJob()
{

}

void MainJob::Init()
{
    g_hook = new Hook;
    g_zhTranslator = new ZhTranslator;

    int *fontEntryAddr = (int *)18483008;
    while(1) {
        if(*fontEntryAddr == 1408011093) {
            break;
        }

        this->thread()->msleep(100);
    }
    //MessageBoxA(NULL, "Font entry ok!", "Title", MB_OK);

    g_hook->LibFuncHookJmp("gdi32.dll", "CreateFontW", (void *)FixedCreateFontW);
    g_hook->LibFuncHookJmp("gdi32.dll", "TextOutW", (void *)FixedTextOutW);
}
